package com.limao.CacheManager;

import java.util.ArrayList;

import com.Hazelcast.Cache;
import com.Hazelcast.CacheFactory;
import com.limao.DBDataClass.IpDateClass;
import com.limao.DBProvider.IpProvider;
import com.limao.Tool.CacheClass;
import com.limao.cache.BasicModule;

public class IpCacheManager extends BasicModule{

	private IpProvider provider;
	private static IpCacheManager instance;
	
	private Cache<String, IpDateClass> IpCacheManager;

    public static IpCacheManager getInstance() {
        return instance;
    }

    public IpCacheManager() {
    	super("IpCacheManager");
    	IpCacheManager = CacheFactory.createCache("cd_IpCacheManager");
		initProvider();
    }

    @Override
	public void initialize() {
        super.initialize();
        instance=this;
    }
    
    public void ClearObjectCache(String ip)
    {
    	IpDateClass tmp = IpCacheManager.get(ip);
    	if(tmp!=null)
    		IpCacheManager.remove(tmp.ip);

    }
    
    //type:0 注册 1登陆 2提现 
    public boolean isDisableIp(String ip,int type)
    {
    	if(CacheClass.isEmpty(ip)) return false;
    	
    	if(IpCacheManager.size()==0)
    	{
    		ArrayList<IpDateClass> list=provider.Load_Ip_All();
    		for(IpDateClass obj:list)
    		{
    			IpCacheManager.put(obj.ip, obj);
    		}
    	}
    	
    	if(IpCacheManager.size()!=0)
    	{
    		IpDateClass tmp = IpCacheManager.get(ip);
        	if(tmp!=null)
        	{
     			if(CacheClass.getLongValue(tmp.etime)>CacheClass.getTime())
    			{
     				switch(type)
     				{
     				case 0:
     					if(CacheClass.getIntValue(tmp.reg)==1)
     					{
     						return true;
     					}
     					break;
     				case 1:
     					if(CacheClass.getIntValue(tmp.auth)==1)
     					{
     						return true;
     					}
     					break;
     				case 2:
     					if(CacheClass.getIntValue(tmp.rmb)==1)
     					{
     						return true;
     					}
     					break;
     				default:
     						
     				}
       			}
    			else
    			{
    				delete_Ip(ip);
    				return false;
    			}
        	}
    	}

    	return false;
     
    }
    
    
     private void delete_Ip(String ip)
     {
    	 provider.delete_Ip(ip);
    	 IpCacheManager.remove(ip);
     }

    
    private void initProvider() {
        if (provider == null ) {
            try {
                provider =IpProvider.getInstance();
            }
            catch (Exception e) {
            	e.printStackTrace();
            }
        }
    }
    

}
